// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV })
const db = cloud.database()

// 云函数入口函数
exports.main = async (event, context) => {
  const { action, ...data } = event
  
  switch (action) {
    case 'list':
      return getAddressList(data)
    case 'add':
      return addAddress(data)
    case 'detail':
      return getAddressDetail(data)
    case 'update':
      return updateAddress(data)
    case 'delete':
      return deleteAddress(data)
    case 'setDefault':
      return setDefaultAddress(data)
    case 'getDefault':
      return getDefaultAddress(data)
    default:
      return {
        success: false,
        message: '未知操作'
      }
  }
}

// 获取地址列表
async function getAddressList({ userId }) {
  try {
    const res = await db.collection('addresses')
      .where({ userId: userId })
      .orderBy('isDefault', 'desc') // 默认地址优先
      .orderBy('createTime', 'desc')
      .get()
      
    return {
      success: true,
      addressList: res.data
    }
  } catch (error) {
    console.error('获取地址列表失败:', error)
    return {
      success: false,
      message: '获取地址列表失败'
    }
  }
}

// 添加地址
async function addAddress({ userId, addressData }) {
  try {
    // 如果设置为默认地址，先取消其他地址的默认状态
    if (addressData.isDefault) {
      await db.collection('addresses')
        .where({ userId: userId, isDefault: true })
        .update({
          data: {
            isDefault: false
          }
        })
    }
    
    const res = await db.collection('addresses').add({
      data: {
        ...addressData,
        userId: userId,
        createTime: db.serverDate(),
        updateTime: db.serverDate()
      }
    })
    
    return {
      success: true,
      addressId: res._id,
      message: '添加地址成功'
    }
  } catch (error) {
    console.error('添加地址失败:', error)
    return {
      success: false,
      message: '添加地址失败'
    }
  }
}

// 获取地址详情
async function getAddressDetail({ userId, addressId }) {
  try {
    const res = await db.collection('addresses')
      .where({
        _id: addressId,
        userId: userId
      })
      .get()
      
    if (res.data.length === 0) {
      return {
        success: false,
        message: '地址不存在'
      }
    }
    
    return {
      success: true,
      address: res.data[0]
    }
  } catch (error) {
    console.error('获取地址详情失败:', error)
    return {
      success: false,
      message: '获取地址详情失败'
    }
  }
}

// 更新地址
async function updateAddress({ userId, addressId, addressData }) {
  try {
    // 如果设置为默认地址，先取消其他地址的默认状态
    if (addressData.isDefault) {
      await db.collection('addresses')
        .where({ userId: userId, isDefault: true })
        .update({
          data: {
            isDefault: false
          }
        })
    }
    
    await db.collection('addresses')
      .where({
        _id: addressId,
        userId: userId
      })
      .update({
        data: {
          ...addressData,
          updateTime: db.serverDate()
        }
      })
      
    return {
      success: true,
      message: '更新地址成功'
    }
  } catch (error) {
    console.error('更新地址失败:', error)
    return {
      success: false,
      message: '更新地址失败'
    }
  }
}

// 删除地址
async function deleteAddress({ userId, addressId }) {
  try {
    await db.collection('addresses')
      .where({
        _id: addressId,
        userId: userId
      })
      .remove()
      
    return {
      success: true,
      message: '删除地址成功'
    }
  } catch (error) {
    console.error('删除地址失败:', error)
    return {
      success: false,
      message: '删除地址失败'
    }
  }
}

// 设置默认地址
async function setDefaultAddress({ userId, addressId }) {
  try {
    // 先取消其他地址的默认状态
    await db.collection('addresses')
      .where({ userId: userId, isDefault: true })
      .update({
        data: {
          isDefault: false
        }
      })
    
    // 设置当前地址为默认
    await db.collection('addresses')
      .where({
        _id: addressId,
        userId: userId
      })
      .update({
        data: {
          isDefault: true,
          updateTime: db.serverDate()
        }
      })
      
    return {
      success: true,
      message: '设置默认地址成功'
    }
  } catch (error) {
    console.error('设置默认地址失败:', error)
    return {
      success: false,
      message: '设置默认地址失败'
    }
  }
}

// 获取默认地址
async function getDefaultAddress({ userId }) {
  try {
    const res = await db.collection('addresses')
      .where({
        userId: userId,
        isDefault: true
      })
      .get()
      
    if (res.data.length > 0) {
      return {
        success: true,
        address: res.data[0]
      }
    } else {
      // 没有默认地址，返回最新添加的地址
      const latestRes = await db.collection('addresses')
        .where({ userId: userId })
        .orderBy('createTime', 'desc')
        .limit(1)
        .get()
      
      if (latestRes.data.length > 0) {
        return {
          success: true,
          address: latestRes.data[0]
        }
      }
      
      return {
        success: true,
        address: null
      }
    }
  } catch (error) {
    console.error('获取默认地址失败:', error)
    return {
      success: false,
      message: '获取默认地址失败'
    }
  }
}